package com.abu.kpaymodel.wxconfig;

import com.github.wxpay.sdk.WXPay;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class WxPayTemplate {

    @Autowired
    private WxConfig wxConfig;

    @Value("${wxpay.notifyUrl}")
    private String notifyUrl;

    public String getCodeUrl(WxPayVo wxPayVo) {

        //       1.封装数据
        WXPay wxpay = new WXPay(wxConfig);
        Map<String, String> data = new HashMap<>();
        data.put("body", wxPayVo.getBody());       //商品描述
        data.put("out_trade_no", wxPayVo.getOut_trade_no());     //订单号
        data.put("total_fee", wxPayVo.getTotal_fee());     //整数金额，单位是分
        data.put("product_id", wxPayVo.getProduct_id());   //商品id
        data.put("notify_url", notifyUrl);     //回调地址
        data.put("device_info", "");        //设备号信息
        data.put("fee_type", "CNY");     //货币
        data.put("spbill_create_ip", "127.0.0.1");   //调用微信支付的终端IP
        data.put("trade_type", "NATIVE");  // 此处指定为扫码支付
        Map<String, String> resp = null;
//        2.执行
        try {
            resp = wxpay.unifiedOrder(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        获取相应的状态码
        String returnCode = resp.get("return_code");
        if (!StringUtils.equals("SUCCESS", returnCode)) {
            log.error("=_= 订单编号{}出现异常", resp.get("out_trade_no"));
            throw new RuntimeException("状态码为FAIL");
        }
//        获取code_url
        String codeUrl = resp.get("code_url");
        if (StringUtils.isBlank(codeUrl)) {
            return null;
        }
        return codeUrl;
    }
}
